import React, { Component, PropTypes } from 'react';
import { Relax } from 'iflux2';
import { Row, Col, Table, Modal, Popconfirm, Menu, Button } from 'antd'
import { List, Map, is } from 'immutable';
import { Link } from 'react-router'
import SectionDialog from '../../component/SectionDialog.js';
import ArticleDialog from '../../component/ArticleDialog.js';
import columns from "../../constants/sectionColumns.js"
import { PageSizeOptions } from 'constant/pagination.js'
import { topSectionsQL, tableSectionsQL, treeSectionsQL } from '../ql.js';

const noop = ()=>{}
@Relax
class ArticleSections extends Component {
    static defaultProps = {
        domain:Map({}),
        sections:List.of(),//所有的栏目数据
        topSections:topSectionsQL,//顶级的栏目数据（pid=0）
        tableSections:tableSectionsQL,
        treeSections:treeSectionsQL,
        addArticleSection:noop,//新增栏目
        updateArticleSection:noop,//编辑栏目
        deleteArticleSection:noop,//删除栏目 
        addArticle:noop,
        fetchArticleSections:noop,
    }

    constructor(props) {
        super(props);
        this.mode = '';//是编辑还是新增栏目：add|update
        this.state = {
            visibleSection:false,
            visibleArticle:false,
            activeId:'',//当前选中的栏目编号
            loading:true,
        }
    }
    componentWillReceiveProps(nextProps) {
        if(!is(this.props.domain,nextProps.domain)){
            //预览的地址发生变化
            this.columns = this.concatColumns(nextProps, columns)
        }
    }
    
    componentDidMount() {
        this.columns = this.concatColumns(this.props, columns)

        this.fetchArticleSections();
    }
    
    
    render() {
        const { tableSections, topSections, treeSections, sections} = this.props;
        const { visibleSection, visibleArticle, activeId, loading } = this.state;
        let activeSection = Map({});
        if(this.mode === 'update' && sections.count() > 0){
            activeSection = sections.find(item=>item.get('id') === activeId)
        }
        // const pagination = {
        //     total: sections.count(),
        //     showSizeChanger: true,
        //     showQuickJumper: true,
        //     showTotal(total) {
        //         return `共 ${total} 条`;
        //     },
        //     onChange:this.pageChange,
        //     pageSizeOptions:PageSizeOptions,
        //     onShowSizeChange:this.pageSizeChange
        // }
        return (
            <div>
                <Row className="table-toolbar">
                    <Col span={12}>
                        <Button type="primary" onClick={()=>{this.showSectionDialog('add')}}>新增栏目</Button>    
                        <Link to="/articles">
                            <Button  type="ghost">文章管理</Button>
                        </Link>
                    </Col>
                </Row>
                <Table
                    rowKey="id"
                    loading={loading}
                    dataSource={tableSections.sortBy(item=>item.get('sort')).toJS()}
                    columns={this.columns}
                />
                <SectionDialog
                    visible={visibleSection}
                    options={topSections}
                    activeId={activeId}
                    section={activeSection}
                    onOk={this.handleSectionOk}
                    onCancel={this.handleSectionCancel}
                 />
                 <ArticleDialog
                    visible={visibleArticle}
                    options={treeSections}
                    activeSectionId={activeId}
                    onOk={this.handleArticleOk}
                    onCancel={this.handleArticleCancel} 
                />
            </div>
        );
    }

    concatColumns = (props, columns) => {
        const { domain } = props;
        return columns.concat([
            {
                title:"操作",
                key:"operation",
                render:(text,record,index) => {
                    var options = [];
                    //系统栏目，不可编辑和删除，不可以新增子栏目
                    if(record.system === 'Y' && record.pid === 0){
                        options = options.concat([
                            <span>新增子栏目</span>,
                            <a href="javascript:;" className="pushl" onClick={()=>{this.showArticleDialog(record.id)}}>新增新文章</a>,
                            <span className="pushl">编辑</span>,
                            <span className="pushl">删除</span>
                        ])
                        
                    }else if(record.pid != 0){
                        //子栏目不可以再新增子栏目
                        options = options.concat([
                            <span>新增子栏目</span>,
                            <a href="javascript:;" className="pushl" onClick={()=>{this.showArticleDialog(record.id)}}>新增新文章</a>,
                            <a href="javascript:;" onClick={()=>{this.showSectionDialog('update',record.id)}}>编辑</a>,
                            <a href="javascript:;">
                                <Popconfirm placement="topRight" title={"您确定要删除该栏目吗？"} onConfirm={()=>{this.confirmDelete(record, index)}} okText="确定" cancelText="取消">
                                    <span>删除</span>
                                </Popconfirm>
                            </a>
                        ])
                    }else{
                        //其余非系统和子栏目，可以正常操作
                        options = options.concat([
                            <a href="javascript:;" onClick={()=>{this.showSectionDialog('add',record.id)}}>新增子栏目</a>,
                            <a href="javascript:;" onClick={()=>{this.showArticleDialog(record.id)}}>新增新文章</a>,
                            <a href="javascript:;" onClick={()=>{this.showSectionDialog('update',record.id)}}>编辑</a>,
                            <a href="javascript:;">
                                <Popconfirm placement="topRight" title={"您确定要删除该栏目吗？"} onConfirm={()=>{this.confirmDelete(record, index)}} okText="确定" cancelText="取消">
                                    <span>删除</span>
                                </Popconfirm>
                            </a>
                        ])
                    }
                    return (
                         <span className="operations">
                            {options}
                            <a className="pushl" target="_blank" href={`${domain.get('domainUrl')}/subject/type${record.url || ''}`}>预览</a>
                        </span>
                    );
                }
            }
        ])
    }
    /**
     * 弹出栏目新增|编辑框
     * @param mode ('add' | 'update')
     */
    showSectionDialog = (mode, activeId='') => {
        this.mode = mode;
         this.setState ({
            visibleSection:true,
            activeId
        })
    }
    /**
     * 弹出新增文章框
     */
    showArticleDialog = (activeId='') => {
         this.setState ({
            visibleArticle:true,
            activeId
        })
    }
    /**
     * 新增|编辑栏目保存回调
     */
    handleSectionOk = (valueFields)=>{
        this.props[`${this.mode}ArticleSection`](valueFields)
            .then(result => {
                this.handleSectionCancel();
            })
            .catch(()=>{});
        
    }
    /**
     * 新增|编辑栏目取消回调
     */
    handleSectionCancel = () => {
        this.mode = '';
        this.setState ({
            visibleSection:false,
            activeId:''
        })
    }
    /**
     * 新增文章保存回调
     */
    handleArticleOk = (valueFields)=>{
        this.props.addArticle(valueFields).then(()=>{
            this.handleArticleCancel();
        });
        
    }
    /**
     * 新增文章取消回调
     */
    handleArticleCancel = () => {
        this.setState ({
            visibleArticle:false,
            activeId:''
        })
    }
    /**
     * 删除栏目
     * @param record object 
     * @param index number  
     */
    confirmDelete = (record, index) =>{
        this.props.deleteArticleSection(record.id);
    }

    fetchArticleSections = () => {
        if(!this.state.loading){
            this.setState({
                loading:true
            })
        }
        this.props.fetchArticleSections()
            .then(reps => {
                this.setState({
                    loading:false
                })
            })
            .catch(error => {
                this.setState({
                    loading:false
                })
            })
    }
    /**
     * @param pageCode 目标页码
     * @param pageSize 页数
     */
    pageChange = (pageCode,pageSize) => {

    }

    /**
     * @param current 页码
     * @param pageSize 页数
     */
    pageSizeChange = (current,pageSize) => {

    }
}


export default ArticleSections;